import React, { useEffect } from "react";
import * as echarts from "echarts";
import "./MyEcharts.css";
let chart = null as any;
function MyEcharts() {
  const myecharts = React.useRef(null);
  useEffect(() => {
    chart = echarts.init(myecharts.current);
    chart.setOption(option);
    initwebsocket();
  }, []);
  const initwebsocket = () => {
    const ws = new WebSocket(
      "ws://localhost:3002/bigscreen/websockets?id=10086"
    );
    ws.onmessage = (e) => {
      const data = JSON.parse(e.data);
      const { legendData } = data;
      const { seriesData } = data;
      option.series.forEach((item, index) => (item.data = seriesData[index]));
      option.xAxis.data = legendData;
      option.legend.data = legendData;
      chart.setOption(option);
    };
  };
  const option = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      icon: "circle",
      data: ["运动区", "宿舍区", "教学区", "吸烟区", "干饭区"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    toolbox: {
      feature: {
        saveAsImage: {},
      },
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "运动区",
        type: "line",
        stack: "Total",
        data: [120, 132, 101, 134, 90, 230, 210],
        smooth: 0.6,
        symbol: "none",
      },
      {
        name: "宿舍区",
        type: "line",
        stack: "Total",
        data: [220, 182, 191, 234, 290, 330, 310],
        smooth: 0.6,
        symbol: "none",
      },
      {
        name: "教学区",
        type: "line",
        stack: "Total",
        data: [150, 232, 201, 154, 190, 330, 410],
        smooth: 0.6,
        symbol: "none",
      },
      {
        name: "吸烟区",
        type: "line",
        stack: "Total",
        data: [320, 332, 301, 334, 390, 330, 320],
        smooth: 0.6,
        symbol: "none",
      },
      {
        name: "干饭区",
        type: "line",
        stack: "Total",
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        smooth: 0.6,
        symbol: "none",
        icon: "circle",
      },
    ],
  };
  return (
    <div>
      <div className="home-left-button">
        <span className="home-left-top-title">
          学生分布情况
          <div className="title-img"></div>
        </span>
      </div>
      <div className="home-left-button-content">
        <div
          id="chart"
          style={{ width: "420px", height: "300px" }}
          ref={myecharts}
        ></div>
      </div>
    </div>
  );
}

export default MyEcharts;
